package com.ruoyi.web.controller.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.OrderConstants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.entity.BO.MemberConsumeBO;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.DO.order.MemberRechargeOrderDO;
import com.ruoyi.common.entity.VO.member.*;
import com.ruoyi.common.entity.VO.product.RechargeProductVO;
import com.ruoyi.common.entity.VO.shop.ShopProductSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopProductVO;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.lianlu.LianluSmsUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.IBackShopProductMapper;
import com.ruoyi.web.controller.member.service.IBackMemberService;
import com.ruoyi.web.controller.order.mapper.IBackShopPetrolOrderMapper;
import com.ruoyi.web.controller.order.service.IBackOrderService;
import com.ruoyi.web.controller.shop.service.IBackShopMemberLabelService;
import com.ruoyi.web.controller.shop.service.IBackShopProductService;
import com.ruoyi.web.controller.tool.IdWorker;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 店铺-会员管理
 */
@Controller
@RequestMapping("/back/shopMember")
public class BackShopMemberController extends BaseController {
    private String prefix = "shop/member";

    @Resource
    private IBackMemberService memberService;

    @Resource
    private IBackShopProductMapper backShopProductMapper;

    @Resource
    private IBackShopProductService backShopProductService;

    @Resource
    private IBackShopPetrolOrderMapper backShopPetrolOrderMapper;

    @Resource
    private IBackOrderService backOrderService;

    @Resource
    private IBackShopMemberLabelService backShopMemberLabelService;

    @Resource
    private LianluSmsUtils lianluSmsUtils;

    /**
     * 会员列表-页面跳转
     *
     * @return
     */
    @RequiresPermissions("back:shopMember:list")
    @GetMapping()
    public String list(ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setShopId(ShiroUtils.getShopId());
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
        List<ShopProductVO> petrolList = backShopProductService.searchList(searchVO);
        petrolList.forEach(x -> x.setProductName(x.getProductCategory() + x.getProductName()));
        mmap.put("petrolTypeList", petrolList);
        MemberLabelSearchVO searchVO2 = new MemberLabelSearchVO();
        searchVO.setShopId(ShiroUtils.getShopId());
        searchVO.setIsEnable(1);
        List<MemberLabelVO> labelList = backShopMemberLabelService.searchList(searchVO2);
        mmap.put("labelList", labelList);
        return prefix + "/list";
    }

    /**
     * 会员关联列表-页面跳转
     *
     * @return
     */
    @RequiresPermissions("back:shopMember:linkList")
    @GetMapping("/linkList/{type}/{memberId}")
    public String linkList(@PathVariable("type") Integer type, @PathVariable("memberId") Long memberId, ModelMap mmap) {
        mmap.put("memberId", memberId);
        MemberDO memberInfo = memberService.selectById(memberId);
        switch (type) {
            case 1:
                //"会员优惠券列表";
                return prefix + "/couponList";
            case 2:
                //"会员加油订单列表";
                ShopProductSearchVO searchVO = new ShopProductSearchVO();
                searchVO.setShopId(ShiroUtils.getShopId());
                searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
                List<ShopProductVO> petrolList = backShopProductService.searchList(searchVO);
                petrolList.forEach(x -> x.setProductName(x.getProductCategory() + x.getProductName()));
                mmap.put("petrolTypeList", petrolList);
                return prefix + "/petrolList";
            case 3:
                //"会员充值订单列表";
                return prefix + "/rechargeList";
            case 4:
                //"会员积分兑换订单列表";
                return prefix + "/creditList";
            case 5:
                //"会员积分记录列表";
                mmap.put("credit", memberInfo.getCredit());
                return prefix + "/credit/recordList";
            case 6:
                //"会员余额记录列表";
                mmap.put("balance", memberInfo.getBalance());
                return prefix + "/balance/recordList";
            default:
                break;
        }
        return "redirect:/back/shop/switchShop";
    }

    /**
     * 查询会员余额列表-数据
     */
    @RequiresPermissions("back:shopMember:linkList")
    @PostMapping("/searchBalanceRecordList")
    @ResponseBody
    public TableDataInfo searchBalanceRecordList(MemberBalanceRecordSearchVO searchVO) {
        startPage();
        List<MemberBalanceRecordVO> list = memberService.searchBalanceRecordList(searchVO);
        return getDataTable(list);
    }

    /**
     * 查询会员积分列表-数据
     */
    @RequiresPermissions("back:shopMember:linkList")
    @PostMapping("/searchCreditRecordList")
    @ResponseBody
    public TableDataInfo searchCreditRecordList(MemberCreditRecordSearchVO searchVO) {
        startPage();
        List<MemberCreditRecordVO> list = memberService.searchCreditRecordList(searchVO);
        return getDataTable(list);
    }

    /**
     * 查询会员列表-数据
     */
    @RequiresPermissions("back:shopMember:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MemberSearchVO memberSearchVO) {
        List<MemberVO> list = new ArrayList<>();
        List<Long> memberIdList = new ArrayList<>();
        String beginTime2 = (String) memberSearchVO.getParams().get("beginTime2");
        String endTime2 = (String) memberSearchVO.getParams().get("endTime2");
        String beginTP2Str = (String) memberSearchVO.getParams().get("beginTP2");
        String endTP2Str = (String) memberSearchVO.getParams().get("endTP2");
        boolean condition1 = null != memberSearchVO.getProductId() && 0 != memberSearchVO.getProductId();
        boolean condition2 = (StringUtils.isNotEmpty(beginTime2) || StringUtils.isNotEmpty(endTime2));
        if (condition1 || condition2) {
            List<MemberConsumeBO> memberList = backShopPetrolOrderMapper.searchMemberList(memberSearchVO);
            if (0 == memberList.size()) {
                return getDataTable(list);
            }
            if (condition1 && !condition2) {
                //只有油品筛选
                for (MemberConsumeBO x : memberList
                ) {
                    memberIdList.add(x.getMemberId());
                }
            } else {
                //包含消费频率筛选
                beginTP2Str = StringUtils.isNotEmpty(beginTP2Str) ? beginTP2Str : "1";
                endTP2Str = StringUtils.isNotEmpty(endTP2Str) ? endTP2Str : "999999";
                int beginTP2 = Integer.valueOf(beginTP2Str);
                int endTP2 = Integer.valueOf(endTP2Str);
                HashMap<Long, Integer> memberCountMap = new HashMap<>();
                if (1 == beginTP2 && 999999 == endTP2) {
                    for (MemberConsumeBO x : memberList
                    ) {
                        memberIdList.add(x.getMemberId());
                    }
                } else {
                    for (MemberConsumeBO x : memberList
                    ) {
                        if (!memberCountMap.containsKey(x.getMemberId())) {
                            memberCountMap.put(x.getMemberId(), 1);
                        } else {
                            memberCountMap.put(x.getMemberId(), memberCountMap.get(x.getMemberId()) + 1);
                        }
                    }
                    Iterator<Map.Entry<Long, Integer>> iterator = memberCountMap.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<Long, Integer> next = iterator.next();
                        if (next.getValue() >= beginTP2 && next.getValue() <= endTP2) {
                            memberIdList.add(next.getKey());
                        }
                    }
                    if (0 == memberIdList.size()) {
                        return getDataTable(list);
                    }
                }

            }
        }
        if (memberIdList.size() > 0) {
            memberSearchVO.setMemberIdArr(memberIdList.toArray(new Long[0]));
        }
        memberSearchVO.setShopId(ShiroUtils.getShopId());
        memberSearchVO.setIsAuth(1);

        startPage();

        list = memberService.searchList(memberSearchVO);
        list.forEach(map ->
        {
            map.setConsumeCount(0);
            map.setTotalAmount(map.getTotalPetrolAmount().add(map.getTotalRechargeAmount()));
        });
        return getDataTable(list);

    }

    /**
     * 页面-选择需要赠送的优惠券
     *
     * @return
     */
    @RequiresPermissions("back:shopMember:sendCoupon")
    @GetMapping("/selectCoupon/{memberIdStr}")
    public String selectCoupon(@PathVariable("memberIdStr") String memberIdStr, ModelMap mmap) {
        mmap.put("memberIdStr", memberIdStr);
        return prefix + "/selectCoupon";
    }

    /**
     * 页面-选择需要赠送的积分商品
     *
     * @return
     */
    @RequiresPermissions("back:shopMember:sendCreditProduct")
    @GetMapping("/selectCreditProduct/{memberIdStr}")
    public String selectCreditProduct(@PathVariable("memberIdStr") String memberIdStr, ModelMap mmap) {
        mmap.put("memberIdStr", memberIdStr);
        return prefix + "/selectCreditProduct";
    }

    /**
     * 页面-选择发送的推广短信
     *
     * @return
     */
    @RequiresPermissions("back:shopMember:sendSms")
    @GetMapping("/selectSmsTemplate/{memberIdStr}")
    public String selectSmsTemplate(@PathVariable("memberIdStr") String memberIdStr, ModelMap mmap) {
        String notifyNum = "获取失败";
        String salesNum = "获取失败";
        try {
            JSONObject response1 = LianluSmsUtils.querySmsBalance(true);
            JSONObject response2 = LianluSmsUtils.querySmsBalance(false);
            if(response1.containsKey("message") && response1.getString("message").equals("success")){
                notifyNum = response1.getString("balance");
            }
            if(response2.containsKey("message") && response1.getString("message").equals("success")){
                salesNum = response2.getString("balance");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mmap.put("memberIdStr", memberIdStr);
        mmap.put("notifyNum",notifyNum);
        mmap.put("salesNum",salesNum);
        return prefix + "/selectLianluSmsTemplate";
    }

    /**
     * 查看会员信息-页面跳转
     */
    @RequiresPermissions("back:shopMember:view")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        MemberDO member = memberService.selectById(id);
        mmap.put("member", member);
        return prefix + "/edit";
    }

    /**
     * 编辑会员-数据
     */
    @RequiresPermissions("back:shopMember:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(MemberVO memberVO) {
        try {
            memberVO.setUpdateBy(ShiroUtils.getSysUser().getUserName());
            memberVO.setUpdateTime(new Date());
            memberService.edit(memberVO);
            return success();
        } catch (BusinessException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 页面-调整会员积分
     */
    @RequiresPermissions("back:shopMember:editCredit")
    @GetMapping("/editCredit/{memberId}")
    public String editCredit(@PathVariable("memberId") Long memberId, ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        MemberDO member = memberService.selectById(memberId);
        mmap.put("member", member);
        return prefix + "/credit/editCredit";
    }

    /**
     * 数据处理-调整会员积分
     */
    @Log(title = "站点-调整会员积分", businessType = BusinessType.UPDATE)
    @RequiresPermissions("back:shopMember:editCredit")
    @PostMapping("/editCredit")
    @ResponseBody
    public AjaxResult editCredit(MemberVO memberVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        try {
            memberVO.setUpdateBy(ShiroUtils.getSysUser().getUserName());
            memberVO.setUpdateTime(new Date());
            memberService.editCredit(memberVO);
            return success();
        } catch (BusinessException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 页面-调整会员余额
     */
    @RequiresPermissions("back:shopMember:editBalance")
    @GetMapping("/editBalance/{memberId}")
    public String editBalance(@PathVariable("memberId") Long memberId, ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        MemberDO member = memberService.selectById(memberId);
        mmap.put("member", member);
        return prefix + "/balance/editBalance";
    }

    /**
     * 页面-调整会员余额
     */
    @RequiresPermissions("back:shopMember:recharge")
    @GetMapping("/recharge/{memberId}")
    public String recharge(@PathVariable("memberId") Long memberId, ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        MemberDO member = memberService.selectById(memberId);
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.RECHARGE.getValue());
        searchVO.setShopId(ShiroUtils.getShopId());
        searchVO.setMemberVipTypeId(member.getVipTypeId());
        searchVO.setIsEnable(1);
        searchVO.setIsDelete(0);
        List<RechargeProductVO> productList = backShopProductMapper.searchRechargeList(searchVO);
        mmap.put("member", member);
        mmap.put("productList", productList);
        return prefix + "/balance/recharge";
    }


    /**
     * 数据处理-调整会员余额
     */
    @Log(title = "站点-调整会员余额", businessType = BusinessType.UPDATE)
    @RequiresPermissions("back:shopMember:editBalance")
    @PostMapping("/editBalance")
    @ResponseBody
    public AjaxResult editBalance(MemberVO memberVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        try {
            memberVO.setUpdateBy(ShiroUtils.getSysUser().getUserName());
            memberVO.setUpdateTime(new Date());
            memberService.editBalance(memberVO);
            return success();
        } catch (BusinessException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 数据处理-创建充值订单
     */
    @Log(title = "站点-调整会员余额", businessType = BusinessType.UPDATE)
    @RequiresPermissions("back:shopMember:recharge")
    @PostMapping("/recharge")
    @ResponseBody
    public AjaxResult recharge(MemberRechargeOrderDO createDO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        createDO.setShopId(ShiroUtils.getShopId());
        if (null == createDO.getMemberId()) {
            return error("请选择会员帐号！");
        }
        MemberDO memberInfo = memberService.selectById(createDO.getMemberId());
        if (null == createDO.getProductId() || 0 == createDO.getProductId()) {
            createDO.setProductId(0L);
            createDO.setProductSn("NULL");
            createDO.setAmount(createDO.getAmount());
            createDO.setGiftCredit(0);
        } else {
            ShopProductSearchVO searchVO = new ShopProductSearchVO();
            searchVO.setShopId(ShiroUtils.getShopId());
            searchVO.setProductId(createDO.getProductId());
            searchVO.setIsDelete(0);
            searchVO.setIsEnable(1);
            searchVO.setMemberVipTypeId(memberInfo.getVipTypeId());
            searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.RECHARGE.getValue());
            RechargeProductVO productInfo = backShopProductMapper.getRechargeProductDetail(searchVO);
            if (null == productInfo) {
                return error("暂不提供该金额的充值,请选择其他");
            }
            if (0 == productInfo.getStock()) {
                return error("该面值的充值金额已抢光");
            }
            //TODO:查看是否送积分
//            if (1 == productInfo.getIsBenefitEnable() && 1 == productInfo.getIsCredit()) {
//                if (null != productInfo.getBenefitCredit() && productInfo.getBenefitCredit() > 0) {
//                    createDO.setGiftCredit(productInfo.getBenefitCredit());
//                } else if (null != productInfo.getBenefitCreditRate() && BigDecimal.ZERO.compareTo(productInfo.getBenefitCreditRate()) < 0) {
//                    createDO.setGiftCredit(createDO.getAmount().multiply(productInfo.getBenefitCreditRate()).toBigInteger().intValue());
//                }
//            }
            //TODO:查看是否送金额
            if (1 == productInfo.getIsBenefitEnable() && 1 == productInfo.getIsAmount()) {
                if (null != productInfo.getBenefitAmount() && productInfo.getBenefitAmount() > 0) {
                    createDO.setGiftAmount(productInfo.getBenefitAmount());
                } else if (null != productInfo.getBenefitAmountRate() && BigDecimal.ZERO.compareTo(productInfo.getBenefitAmountRate()) < 0) {
                    createDO.setGiftAmount(createDO.getAmount().multiply(productInfo.getBenefitAmountRate()).toBigInteger().intValue());
                }
            }
            createDO.setProductSn(productInfo.getProductSn());
            createDO.setAmount(productInfo.getPrice());
        }
        try {
            long orderId;
            try {
                orderId = IdWorker.getFlowIdWorkerInstance().nextId();
            } catch (Exception e) {
                throw new BusinessException("网络超时,请重新再试！");
            }
            String time = DateUtils.dateTimeNow();
            createDO.setId(orderId);
            createDO.setDiscountAmount(BigDecimal.ZERO);
            createDO.setDiscountDesc("无");
            createDO.setPayAmount(createDO.getAmount());
            createDO.setOrderSn(OrderConstants.SnPrefix.CHARGE_MEMBER.getValue() + time + NumberUtils.generateCode(5));
            createDO.setPaySn(OrderConstants.SnPrefix.PAY_BACK.getValue() + time + NumberUtils.generateCode(4));
            createDO.setOrderStatus(OrderConstants.OrderStatusEnum.COMPLETE.getValue());
            createDO.setPayStatus(OrderConstants.OrderPayStatusEnum.COMPLETE.getValue());
            createDO.setCreateTime(new Date());
            createDO.setPayTime(new Date());
            createDO.setCreateBy("后台充值");
            backOrderService.rechargeHandle(createDO);
            return success("后台充值成功！");
        } catch (BusinessException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 数据处理-会员导出
     *
     * @return
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MemberSearchVO memberSearchVO) {
        if (StringUtils.isNotEmpty(memberSearchVO.getMemberIdStr())) {
            if (memberSearchVO.getMemberIdStr().contains(",")) {
                Long[] memberIdArr = Convert.toLongArray(memberSearchVO.getMemberIdStr());
                if (memberIdArr.length > 100) {
                    error("导出数据不能超过100条！");
                }
                memberSearchVO.setMemberIdArr(memberIdArr);
            }
        }
        String sheetName = "";
        Map<String, Object> map = memberSearchVO.getParams();
        if (map.containsKey("beginTime") && map.containsKey("endTime")) {
            sheetName += map.get("beginTime") + "到" + map.get("endTime") + "注册的会员";
        } else if (map.containsKey("month")) {
            sheetName += map.containsKey("month") + "月份注册的会员";
        } else {
            sheetName += "自定义导出会员";
        }
        memberSearchVO.setShopId(ShiroUtils.getShopId());
        List<MemberExportVO> orderList = memberService.searchMemberExportList(memberSearchVO);
        ExcelUtil<MemberExportVO> util = new ExcelUtil<>(MemberExportVO.class);
        return util.exportExcel(orderList, sheetName);
    }
}
